﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using Icoders.MarketTracker.Core.MasterData;
using Icoders.MarketTracker.Core.Repository.MasterDataRepositories;
using Icoders.MarketTracker.Core.Validation;
using Icoders.MarketTracker.Web.Lib;
using Icoders.MarketTracker.Web.Lib.Security;
using Icoders.MarketTracker.Web.Lib.Services;
using Icoders.MarketTracker.Web.Lib.Validation;


namespace Icoders.MarketTracker.Web.Controllers
{
    public class AccountController : Controller
    {
        //
        // GET: /Account/
        private IUserRepository _userRepository;
        private IAuditTrailRepository _auditTrailRepository;
        private IDropDownService _dropDownService;
        CodersEncrypt passEncrypt = new CodersEncrypt();

        public AccountController(IUserRepository userRepository, IAuditTrailRepository auditTrailRepository, IDropDownService dropDownService)
        {
            _userRepository = userRepository;
            _auditTrailRepository = auditTrailRepository;
            _dropDownService = dropDownService;
        }

        private void Bind()
        {
            ViewBag.UserTypeList = _dropDownService.EnumToList<UserType>();
        }

        public ActionResult Login()
        {
            return View(new LoginModel());
        }
        [HttpPost]
        public ActionResult Login(LoginModel login, string returnUrl)
        {
            
            if (ModelState.IsValid)
            {
                string pass = passEncrypt.EncryptThings(login.Password);
                if (_userRepository.IsLogin(login.Username, passEncrypt.EncryptThings(login.Password)))
                {
                    FormsAuthentication.SetAuthCookie(login.Username, false);
                    if (Request.Browser.IsMobileDevice)
                        return RedirectToAction("Index", "MHome", new { area = "Mobile" });
                    if (Url.IsLocalUrl(returnUrl))
                        return Redirect(returnUrl);
                    else
                    {
                        Saveaudit("User Login", login.Username, ActionType.Login);
                        return RedirectToAction("Index", "Home");
                    }
                }
                else
                {
                    ValidationSummary.DisplayValidationResult("Wrong username or password", ModelState);
                    return View(login);

                }

            }
            ValidationSummary.DisplayValidationResult("Wrong username or password", ModelState);
            return View(new LoginModel());
        }

        public ActionResult LogOut()
        {
            FormsAuthentication.SignOut();
            Session.Abandon();

            // clear authentication cookie
            HttpCookie cookie1 = new HttpCookie(FormsAuthentication.FormsCookieName, "");
            cookie1.Expires = DateTime.Now.AddYears(-1);
            Response.Cookies.Add(cookie1);

            // clear session cookie (not necessary for your current problem but i would recommend you do it anyway)
            HttpCookie cookie2 = new HttpCookie("ASP.NET_SessionId", "");
            cookie2.Expires = DateTime.Now.AddYears(-1);
            Response.Cookies.Add(cookie2);

            FormsAuthentication.RedirectToLoginPage();
           return RedirectToAction("login");
        }
        public ActionResult Edit(int id)
        {
            Bind();
            User user = _userRepository.GetById(id);
            return View(user);
        }
        [HttpPost]
        public ActionResult Edit(User model)
        {
            try
            {
                model.Password = passEncrypt.EncryptThings(model.Password);
                model.ConfirmPassword = passEncrypt.EncryptThings(model.ConfirmPassword);
                _userRepository.Save(model);
                Saveaudit("User Edit", model.Username, ActionType.Login);
                Saveaudit("Edited Users", model.Username, ActionType.Updated);
            }
            catch (DomainValidationException dve)
            {
                Bind();
                ValidationSummary.DisplayDomainValidationResult(dve, ModelState);
                return View(model);
            }
            catch (Exception ex)
            {
                Bind();
                ValidationSummary.DisplayValidationResult(ex.Message, ModelState);
                return View(model);
            }
            return RedirectToAction("Index", "Home");
        }
        [Authorize]
        public ActionResult ChangePassword()
        {
            return View(new ChangePassword());
        }
        [HttpPost]
        [Authorize]
        public ActionResult ChangePassword(ChangePassword model, string returnUrl)
        {
            try
            {
                _userRepository.ChangePassword(HttpContext.User.Identity.Name, passEncrypt.EncryptThings(model.OldPassword), passEncrypt.EncryptThings(model.Password));
                Saveaudit("Changed Password", HttpContext.User.Identity.Name, ActionType.Updated);
                if (Url.IsLocalUrl(returnUrl))
                    return Redirect(returnUrl);
                   
            }
            catch (DomainValidationException dve)
            {
                ValidationSummary.DisplayDomainValidationResult(dve, ModelState);
            }
             return RedirectToAction("Index", "Home");
        }

        public string Unauthorized()
        {
            //need to have an admin user tht will take all the login attempts the system is getting 
           //Saveaudit("", HttpContext.User.Identity.Name, ActionType.Updated);
            return "";
        }
        public void Saveaudit(string description, string username, ActionType actionType)
        {
            //  private IUserRepository _userRepository;
            //private IAuditTrailRepository _auditTrailRepository;
            // Saveaudit("Changed Password", HttpContext.User.Identity.Name, ActionType.Updated);
            try
            {
                User user = _userRepository.GetByUsername(username);
                AuditTrail auditTrail = new AuditTrail();
                auditTrail.Description = description;
                auditTrail.UserId = user.Id;
                auditTrail.ActionTypeId = Convert.ToInt32(actionType);
                _auditTrailRepository.Save(auditTrail);
            }
            catch (Exception)
            {
                throw;
            }
        }

    }
}
